<template>
  <div class="flex flex-wrap items-center">
    <div v-if="showSystemUsers">
      <el-tag
        v-for="(user, index) in systemUsers"
        :key="user.employeeId"
        closable
        @close="handleRemoveUser(index)"
        class="mr-10px"
      >
        <el-tooltip :content="user.employeeName">
          {{ user.employeeName }} {{ user.proportion }}%
        </el-tooltip>
      </el-tag>
    </div>

    <el-tooltip content="选择员工" v-if="canAdd">
      <el-button @click="openSpuTableSelect" link>
        <Icon
          icon="svg-icon:yuangongshibie"
          :size="iconSzie"
          :color="
            systemUsers.length > 0 ? 'var(--el-color-primary)' : 'var(--el-text-color-regular)'
          "
        />
      </el-button>
    </el-tooltip>
  </div>
  <!-- 员工选择对话框（表格形式） -->
  <SystemUserSelect
    ref="SystemUserSelectRef"
    :multiple="limit != 1"
    @change="handleSystemUserSelected"
  />
</template>
<script lang="ts" setup>
import SystemUserSelect from './systemUserSelect.vue'
import { propTypes } from '@/utils/propTypes'
import { oneOfType } from 'vue-types'
import { isArray } from '@/utils/is'

// 员工橱窗，一般用于与员工建立关系时使用
// 提供功能：展示员工列表、添加员工、移除员工
defineOptions({ name: 'SystemUserShowcase' })

const props = defineProps({
  modelValue: oneOfType<number | Array<number>>([Number, Array]).isRequired,
  // 限制数量：默认不限制
  limit: propTypes.number.def(Number.MAX_VALUE),
  disabled: propTypes.bool.def(false),
  showSystemUsers: propTypes.bool.def(true),
  iconSzie: propTypes.number.def(24)
})

// 计算是否可以添加
const canAdd = computed(() => {
  // 情况一：禁用时不可以添加
  if (props.disabled) return false
  // 情况二：未指定限制数量时，可以添加
  if (!props.limit) return true
  // 情况三：检查已添加数量是否小于限制数量
  return systemUsers.value.length < props.limit
})

// 员工列表
const systemUsers = ref<any[]>([])

watch(
  () => props.modelValue,
  async () => {
    const users = isArray(props.modelValue)
      ? // 情况一：多选
        props.modelValue
      : // 情况二：单选
        props.modelValue
        ? [props.modelValue]
        : []
    // 不需要返显
    console.log(users)
    // systemUsers.value = users
    if (users.length === 0) {
      systemUsers.value = []
      return
    }
    // 只有员工发生变化之后，才去查询员工
    const ids: any = users.map((ele: any) => {
      return ele.employeeId
    })
    if (
      systemUsers.value.length === 0 ||
      systemUsers.value.some((user) => !ids.includes(user.employeeId!))
    ) {
      systemUsers.value = users
    }
  },
  { immediate: true }
)

/** 员工表格选择对话框 */
const SystemUserSelectRef = ref()
// 打开对话框
const openSpuTableSelect = () => {
  console.log(systemUsers.value)
  SystemUserSelectRef.value.open(systemUsers.value)
}
defineExpose({ openSpuTableSelect })
/**
 * 选择员工后触发
 *
 * @param spus 选中的员工列表
 */
const handleSystemUserSelected = (users: any[]) => {
  systemUsers.value = isArray(users) ? users : [users]
  emitSpuChange()
}

/**
 * 删除员工
 *
 * @param index 员工索引
 */
const handleRemoveUser = (index: number) => {
  systemUsers.value.splice(index, 1)
  emitSpuChange()
}
const emit = defineEmits(['update:modelValue', 'change'])
const emitSpuChange = () => {
  if (props.limit === 1) {
    const user = systemUsers.value.length > 0 ? systemUsers.value[0] : null
    emit('update:modelValue', user?.employeeId || 0)
    emit('change', user)
  } else {
    emit(
      'update:modelValue',
      systemUsers.value.map((user) => {
        return {
          employeeId: user.employeeId,
          proportion: user.proportion,
          employeeName: user.employeeName
        }
      })
    )
    emit('change', systemUsers.value)
  }
}
</script>

<style lang="scss" scoped></style>
